#include <glib.h>
#include <stdlib.h>
#include <string.h>
#include "Token.h"

short int matches_equal(Vector* matches1, Vector* matches2);

short int matches_equal(Vector* matches1, Vector* matches2)
{
  int i = 0;
  while (1) {
    const char* str1 = (const char*)vector_get(matches1, i);
    const char* str2 = (const char*)vector_get(matches2, i);
    if (str1 == NULL && str2 == NULL)
      return 1;
    if (str1 == NULL)
      return 0;
    if (str2 == NULL)
      return 1;
    if (strcmp(str1, str2) != 0)
      return 0;
    i++;
  }
  return 0;
}


/*****************************************************************
 * Public API.
 *****************************************************************/
Token* token_new(const char* type, Vector* matches)
{
  Token* token   = (Token*)g_malloc0(sizeof(Token));
  token->type    = type ? strdup(type) : NULL;
  token->matches = matches;
  return token;
}

void token_free(Token* token)
{
  if (!token)
    return;
  if (token->type)
    free(token->type);
  if (token->matches) {
    int n = -1;
    while (vector_get(token->matches, ++n))
      vector_delete(token->matches, n);
    vector_free(token->matches);
  }
  g_free(token);
}

short int token_compare(Token* token1, Token* token2)
{
  if (strcmp(token1->type, token2->type) != 0)
    return 0;
  if (!token2->matches)
    return 1;
  return matches_equal(token1->matches, token2->matches);
}
